﻿#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include "Snake.h"
#include "GameBase.h"
#include "GameMap.h"

#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77


struct Linkedlist* createLinkedlist(){
	struct Linkedlist *pList = NULL;
	pList = (struct Linkedlist*)malloc(sizeof(struct Linkedlist));
	if (pList != NULL){
		memset(pList, 0, sizeof(struct Linkedlist));
	}
	else{
		printf("Error\n");
		return NULL;
	}
	return pList;
}


int addElement(struct Linkedlist* pList, int position, struct Snakebody element){
	int ret = FALSE;
	int i = 0;
	struct Snakebody* pPreNode = NULL;
	struct Snakebody* pNewNode = NULL;
	if (pList != NULL){
		if (position >= 0 && position <= pList->currentElement){
			pNewNode = (struct Snakebody*)malloc(sizeof(struct Snakebody));
			if (pNewNode != NULL){
				*pNewNode = element;
				pNewNode->next = NULL;
				pPreNode = &(pList->headerNode);
				for (i = 0; i < position; i++){
					pPreNode = pPreNode->next;
				}
				pNewNode->next = pPreNode->next;
				pPreNode->next = pNewNode;
				pList->currentElement++;
				ret = TRUE;
			}
			else{
				printf("ERROR\n memory\n");
				return ret;
			}
		}
		else{
			printf("ERROR\n index\n");
		}
	}
	return ret;
}


void removeElement(struct Linkedlist *pList, int position){
	int i = 0;
	int arrayCount = 0;
	struct Snakebody* pNode = NULL;
	struct Snakebody* delNode = NULL;
	if (pList != NULL){
		arrayCount = pList->currentElement;
		if (position >= 0 && position < arrayCount){
			pNode = &(pList->headerNode);
			for (i = 0; i < position; i++){
				pNode = pNode->next;
			}
			delNode = pNode->next;
			free(delNode);
			pList->currentElement--;
		}
		else{
			printf("ERROR\n");
		}
	}
}


void clearLinkedlist(struct Linkedlist *pList){
	if (pList != NULL){
		for (; pList->currentElement > 0;)
			removeElement(pList, 0);
	}
}


void movedirec(void){
	struct Snakebody headerNode = { 5, 5 };
	struct Snakebody *ptr = &headerNode;

	char c;
	if (_kbhit()){
		c = _getch();
		if (c == 224){
			c = _getch();
			switch (c){
			case LEFT: ptr->x -= 1;
				break;
			case RIGHT:ptr->x += 1;
				break;
			case UP:ptr->y -= 1;
				break;
			case DOWN:ptr->y += 1;
				break;
			default:
				break;
			}
		}
	}
}



void moveNode(void){
	struct Snakebody headerNode = {5,5};
	struct Snakebody *ptr = &headerNode;
	int temp1, temp2;
	temp1 = ptr->x;
	temp2 = ptr->y;
	headerNode.next->x = temp1;
	headerNode.next->y = temp2;
}